package com.gethb.prod.service.impl;

import java.util.Date;
import javax.annotation.Resource;

import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.gethb.data.dao.LoginMapper;
import com.gethb.data.dao.UserMapper;
import com.gethb.data.mdo.UserInfDo;
import com.gethb.data.mdo.UserLoginDo;
import com.gethb.prod.service.IUserLoginService;
import com.gethb.prod.vo.LoginInVo;
import com.gethb.pub.utils.BaseInVo;
import com.gethb.pub.utils.JWTUtil;


@Component("userLoginService")
public class UserLoginServiceImpl implements IUserLoginService {

    private static final Logger LOG = LoggerFactory.getLogger(UserLoginServiceImpl.class);

    @Resource
    UserMapper userMapper;//接口

    @Resource
    LoginMapper loginMapper;//接口

    @Override
    public String adminLogin(LoginInVo inVo) throws Exception {
        if (!"Jack".equals(inVo.getPhone())) {
            return null;
        }
        if (!"75D460E889EB4BD352ACC58808650E4E".equals(inVo.getPassword())) {
            return null;
        }
        UserInfDo user = new UserInfDo();
        user.setId("Jack001");
        user.setMblphNo("Jack");
        user.setName("Jack");
        // 查询token记录，如果存在则进行token更新，否则进行新增
        return getLoginToken(user);
    }

    @Override
    public String userLogin(LoginInVo inVo) throws Exception {
        LOG.info("start用户登陆");

        // 根据手机号查询用户信息
        UserInfDo user = userMapper.findByMbphNoDo(inVo.getPhone());
        // 检查用户与密码
        if (null == user || !inVo.getPassword().equals(user.getPassword())) {
            return null;
        }
        // 查询token记录，如果存在则进行token更新，否则进行新增
        return getLoginToken(user);
    }

    private String getLoginToken(UserInfDo user) throws Exception {
        UserLoginDo userLogin = loginMapper.findLoginTokenInf(user.getId());
        String token;
        if (null == userLogin) {
            LOG.info("用户首次登陆，新增登陆token信息");
            token = addLoginTokenInf(user);
        } else {
            LOG.info("非首次登陆，更新登陆token信息");
            token = updateLoginTokenInf(userLogin);
        }
        return token;
    }


    public String verifyToken(String token) throws Exception {
        //
        if (token == null || "".equals(token)) {
            return null;
        }
        //
        Claims claims = JWTUtil.verifyToken(token);
        // token已过期
        Date nowDate = new Date();
        //
        if (nowDate.after(claims.getExpiration())) {
            return null;
        }
        String userId = claims.getId();
        // 单点登录
        UserLoginDo userLoginDo = loginMapper.findLoginTokenInf(userId);
//
        if (!token.equals(userLoginDo.getTokenId())) {
            return null;
        }
        //
        Date expired = userLoginDo.getExpate();
        if (expired == null) {
            return null;
        }
        //
        if (nowDate.after(expired)) {
            return null;
        }
        return userLoginDo.getId();
    }

    /**
     * 更新token
     *
     * @return token
     */
    private String updateLoginTokenInf(UserLoginDo userLogin) throws Exception {
        LOG.info("非首次登陆，更新token开始");
        String token = JWTUtil.generToken(userLogin.getId(),
                userLogin.getName(), userLogin.getMblphNo());
        LOG.info("更新生成的Token为：" + token);
        userLogin.setTokenId(token);
        userLogin.setLoginSum(userLogin.getLoginSum() + 1);
        Date nowDate = new Date();
        userLogin.setTms(nowDate);
        long expired = nowDate.getTime() + JWTUtil.keeptime;
        userLogin.setExpate(new Date(expired));
        loginMapper.updateLoginTokenInf(userLogin);
        return token;
    }

    /**
     * 用户首次登陆，新增登陆token信息
     */
    private String addLoginTokenInf(UserInfDo userInfDo) throws Exception {
        LOG.info("用户首次登陆，新增登陆token信息开始");
        String token = JWTUtil.generToken(userInfDo.getId(),
                userInfDo.getName(), userInfDo.getMblphNo());
        LOG.info("首次登陆生成的Token为：" + token);
        UserLoginDo loginDo = new UserLoginDo();
        loginDo.setId(userInfDo.getId());
        loginDo.setName(userInfDo.getName());
        loginDo.setMblphNo(userInfDo.getMblphNo());
        Date nowDate = new Date();
        loginDo.setFirstDate(nowDate);

        loginDo.setLoginSum(1);
        long expired = nowDate.getTime() + JWTUtil.keeptime;
        loginDo.setExpate(new Date(expired));
        loginDo.setTokenId(token);

        loginMapper.addUsersLoginInf(loginDo);
        LOG.info("用户首次登陆，新增登陆token信息结束");
        return token;
    }

}